package service.mailing;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import service.configuration.IConfiguration;

@Service
public class Mailer implements IMailer {
	
	@Resource
	JavaMailSender mailSender;
	
	@Resource
	IConfiguration config;
	
	public void sendTextMail(String toAddress, String subject, String text) {
		
		SimpleMailMessage message = new SimpleMailMessage();
		
		message.setTo(toAddress);
		message.setSubject(subject);
		message.setText(text);
		mailSender.send(message);
	}

	
	public void sendHtmlMail(String toAddress, String subject, String body) {
		MimeMessage message = mailSender.createMimeMessage();
		MimeMessageHelper helper;
		
		// DEBUG MODE
		if(config.isApplicationDebug()) {
			toAddress = config.getApplicationAdminMail();
		}
		
		try {
			helper = new MimeMessageHelper(message, true);
			helper.setSubject(subject);
			helper.setTo(toAddress);
			helper.setText(body, true);
		} catch (MessagingException e) {
			e.printStackTrace();
		}

		mailSender.send(message);
	}
}
